﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using System.Threading.Tasks;
using SonCa.SocialNetwork.Web.Chat.Presenters;
using SonCa.SocialNetwork.Web.Chat;

namespace SonCa.SocialNetwork.Web
{
    [HubName("chatHub")]
    public class chat : Hub
    {
        public static string currentID = "";

        public Task JoinGroup()
        {
            return Groups.Add(Context.ConnectionId, "foo");
        }

        public override Task OnConnected()
        {
            UserChatPresenter.userObj = UserChatPresenter.userObj.GroupBy(item => item.userID).Select(n => n.First()).ToList();
            //var newUsers = UserChatPresenter.userObj.Select(item => item.userID).ToList();
            UserChatProperties user = UserChatPresenter.userObj.Where(item => item.sessionID == HttpContext.Current.Request.Cookies["ASP.NET_SessionId"].Value.ToString()).FirstOrDefault();
            user.connectionID = Context.ConnectionId;
            return Clients.All.joined(Context.ConnectionId, null);
        }

        public void Send(string content , string groupName)
        {
            if (Clients != null)
            {
                Clients.Group(groupName).addMessage(content, groupName,currentID);
            }
        }

        public void CreateGroup(string currentUserId, string toConnectTo)
        {
            currentID = currentUserId;
            bool isOnline = false;
            string strGroupName = GetUniqueGroupName(currentUserId, toConnectTo);            
            string connectionId_To = UserChatPresenter.userObj.Where(item => item.userID == toConnectTo).Select(item => item.connectionID).SingleOrDefault();
            if (!string.IsNullOrEmpty(connectionId_To))
            {
                Groups.Add(Context.ConnectionId, strGroupName);
                Groups.Add(connectionId_To, strGroupName);
                isOnline = true;
                Clients.Caller.setChatWindow(strGroupName, toConnectTo, isOnline);
            }
            else
            {                
                Clients.Caller.setChatWindow(strGroupName, toConnectTo, isOnline);
            }
        }

        private string GetUniqueGroupName(string currentUserId, string toConnectTo)
        {
            return (currentUserId.GetHashCode() ^ toConnectTo.GetHashCode()).ToString();
        }
    }
}